One useful application of the Google Docs API is to merge information from oneor more data sources into a document.
This page outlines how you can take data from an external source and insert itinto an existing template document.
A template is a special type of document containing the same fixed text for all documents created from the template, along with designated placeholderswhere other dynamic text can be placed. For example, a contract template might have fixed content, along with spots for the receiver's name, address, andother details. Your app can then merge customer-specific data into the templateto create finished documents.
There are several reasons why this approach is useful:
It's easy for designers to fine-tune a document's design usingthe Google Docs editor. This is much easier than tuning parameters inyour app to set the rendered layout.
Separating content from presentation is a well-known designprinciple with many benefits.
A basic recipeHere's an example of how you can use the Docs API to merge data into a document:
Create your document usingplaceholder content to help you with the design and format. Any text formatting you want to replace is preserved.
For each element you'll be inserting, replace the placeholder content with atag. Be sure to use strings that are unlikely to occur normally. For example,{{account-holder-name}} might be a good tag.
In your code, use the Google Drive API to make a copy of the document.
In your code, use the Docs API's batchUpdate() method withthe document name and include aReplaceAllTextRequest.
Document IDs reference a document and they can be derived from the URL
https://docs.google.com/document/d/documentId/edit You can perform multiple replacements in the same BatchUpdate request for efficiency. See batch request best practices for how to batch API calls togetherExampleConsider the following example, which replaces 2 fields across all tabs of atemplate with real values to generate a finished document.
To perform this merge, you can use the code below.
JavaString customerName = "Alice";DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");String date = formatter.format(LocalDate.now());List requests = new ArrayList();// One option for replacing all text is to specify all tab IDs.requests.add(new Request().setReplaceAllText(new ReplaceAllTextRequest().setContainsText(new SubstringMatchCriteria().setText("{{customer-name}}").setMatchCase(true)).setReplaceText(customerName).setTabsCriteria(new TabsCriteria().addTabIds(TAB_ID_1).addTabIds(TAB_ID_2).addTabIds(TAB_ID_3))));// Another option is to omit TabsCriteria if you are replacing across all tabs.requests.add(new Request().setReplaceAllText(new ReplaceAllTextRequest().setContainsText(new SubstringMatchCriteria().setText("{{date}}").setMatchCase(true)).setReplaceText(date)));BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();service.documents().batchUpdate(documentId, body.setRequests(requests)).execute();Node.js let customerName = 'Alice'; let date = yyyymmdd() let requests = [// One option for replacing all text is to specify all tab IDs.{ replaceAllText: {containsText: { text: '{{customer-name}}', matchCase: true,},replaceText: customerName,tabsCriteria: { tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],}, },},// Another option is to omit TabsCriteria if you are replacing across all tabs.{ replaceAllText: {containsText: { text: '{{date}}', matchCase: true,},replaceText: date, },}, ]; google.options({auth: auth}); google .discoverAPI( 'https://docs.googleapis.com/$discovery/rest?version=v1&key={YOUR_API_KEY}') .then(function(docs) {docs.documents.batchUpdate({ documentId: '1yBx6HSnu_gbV2sk1nChJOFo_g3AizBhr-PpkyKAwcTg', resource: {requests, },},(err, {data}) => { if (err) return console.log('The API returned an error: ' + err); console.log(data);}); });Pythoncustomer_name = 'Alice'date = datetime.datetime.now().strftime("%y/%m/%d")requests = [# One option for replacing all text is to specify all tab IDs.{'replaceAllText': {'containsText': {'text': '{{customer-name}}','matchCase': 'true'},'replaceText': customer_name,'tabsCriteria': {'tabIds': [TAB_ID_1, TAB_ID_2, TAB_ID_3],},}},# Another option is to omit TabsCriteria if you are replacing across all tabs.{'replaceAllText': {'containsText': {'text': '{{date}}','matchCase': 'true'},'replaceText': str(date),}}]result = service.documents().batchUpdate(documentId=document_id, body={'requests': requests}).execute()Note: For documents with multiple tabs,ReplaceAllTextRequestby default applies to all tabs. See the request documentation for moreinformation about how to work with tabs.Manage templatesFor template documents the application defines and owns, createthe template using a dedicated account representing the application.Service accountsare a good choice and avoid complications with Google Workspace policies thatrestrict sharing.
When you create instances of documents from templates, always useend-user credentials. This gives users full control over theresulting document and prevents scaling issues related to per-userlimits in Drive.
To create a template using a service account, perform the following steps withthe application credentials:
Create a document usingdocuments.create in the Docs API.Update the permissions to allow the document recipients to read it usingpermissions.create inthe Drive API.Update the permissions to allow template authors to write to it usingpermissions.create inthe Drive API.Edit the template as required.To create an instance of the document, perform the following stepswith the user credentials:
Create a copy of the template usingfiles.copy in the Drive API.Replace values usingdocuments.batchUpdatein the Docs API.